import cloud from '@lafjs/cloud'
import PizZip from 'pizzip';
import Docxtemplater from 'docxtemplater';
const fs = require('fs')

import {
  Document, Packer, Table, TableCell, TableRow, Paragraph, WidthType, TextRun,
  AlignmentType,
} from 'docx';

const bucketName = 'file' // 不带 Laf 应用 appid
const Bucket = `dhkno3mf-${bucketName}`// 拼接文件桶名字
let dataInfo

export async function main(ctx: FunctionContext) {
  dataInfo = ctx.body
  if (dataInfo.type == 'docx') {
    return docxFunc()
  } else {
    return docxtemplaterFunctions()
  }

}

//使用docx
async function docxFunc() {
  //生成表格的children
  function setChild(list) {
    let size = 100 / dataInfo.data.table.header.length
    let rows = []
    list.forEach(element => {
      rows.push(
        new TableCell({
          children: [new Paragraph(element ? element.toString() : "")],
          width: { size, type: WidthType.PERCENTAGE },
        }))
    });
    return rows
  }

  let body = []
  dataInfo.data.table.data.forEach(element => {
    body.push(
      new TableRow({
        children: setChild(element)
      }),
    )
  });

  //表头
  let header = new TableRow({
    children: setChild(dataInfo.data.table.header)
  })
  let rows = [header, ...body]

  const table = new Table({ rows, });

  // 创建文档
  const doc = new Document({
    sections: [{
      children: [
        new Paragraph({
          children: [
            new TextRun({
              text: "学员出勤记录表",
              bold: true,
              size: 45, // 字体大小
            }),
          ],
          alignment: AlignmentType.CENTER,
        }),

        new Paragraph({
          children: [
            new TextRun({
              text: "标号：",
            }),
            new TextRun({
              text: `职业（等级）：${dataInfo.data.occupationalLevel} `,
            }),
            new TextRun({
              text: `开班日期：${dataInfo.data.classOpeningTime} `,
            }),
            new TextRun({
              text: `班主任：${dataInfo.data.teachingTeacher}`,
            }),
          ],
          spacing: {
            before: 240, // 设置段落前的间距，单位是磅
            after: 240, // 设置段落后的间距，单位是磅
          },
        }),
        table
      ],
    }],
  });
  // 将文档打包并写入文件
  let buffer = await Packer.toBuffer(doc)
  const bucket = cloud.storage.bucket(Bucket)
  await bucket.writeFile(dataInfo.fileName, buffer, {
    ContentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  })
  const url = bucket.externalUrl(dataInfo.fileName)
  return cloud.utils.requestReturn({ data: url })
}

//使用docxtemplater
async function docxtemplaterFunctions() {
  const res = await cloud.fetch({
    url: dataInfo.templateURL,
    method: 'GET',
    responseType: 'arraybuffer',
  })

  // 使用 PizZip 加载模板
  const zip = new PizZip(res.data);

  // 创建 Docxtemplater 实例
  const doc = new Docxtemplater(zip, { paragraphLoop: true, lineBreaks: true });

  // 动态赋值
  doc.render(dataInfo.data); // data 是一个对象，包含了你要填入模板的数据

  // 生成输出的 Word 文件
  const output = doc.getZip().generate({ type: 'nodebuffer' });

  // 获取存储桶
  await cloud.utils.ossDel(Bucket, dataInfo.fileName) // 删除旧文件
  const bucket = cloud.storage.bucket(Bucket)
  await bucket.writeFile(dataInfo.fileName, output, {
    ContentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  })

  const url = bucket.externalUrl(dataInfo.fileName)  //永久访问链接
  return cloud.utils.requestReturn({ data: url })
}
